package com.ztom.top100;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 二叉树展开为链表
 * <p>
 * https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/
 *
 * @author ZhangTao
 */
public class Code44Flatten {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public void flatten2(TreeNode root) {
        if (root == null) {
            return;
        }

        // 先序遍历收集节点
        Deque<TreeNode> queue = new LinkedList<>();
        preorder(queue, root);
        // 生成链表
        TreeNode pre = queue.pollLast();
        while (!queue.isEmpty()) {
            pre.left = null;
            pre.right = queue.pollLast();
            pre = pre.right;
        }
    }

    private void preorder(Deque<TreeNode> collect, TreeNode node) {
        if (node == null) {
            return;
        }

        collect.addFirst(node);
        preorder(collect, node.left);
        preorder(collect, node.right);
    }

    /**
     * 原地修改
     *
     * @param root
     */
    public void flatten1(TreeNode root) {
        if (root == null) {
            return;
        }

        // 先序遍历的同时修改为链表
        Deque<TreeNode> stack = new LinkedList<>();
        stack.push(root);
        TreeNode pre = null;
        while (!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            if (pre != null) {
                pre.left = null;
                pre.right = cur;
            }
            pre = cur;

            if (cur.right != null) {
                stack.push(cur.right);
            }
            if (cur.left != null) {
                stack.push(cur.left);
            }
        }
    }

    /**
     * 找到前驱节点: 先序遍历中, 左子树的最右叶子节点是右树的前驱节点
     * <p>
     * 可以省掉栈
     *
     * @param root
     */
    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }

        TreeNode cur = root;
        while (cur != null) {
            // 存在左子树
            if (cur.left != null) {
                TreeNode left = cur.left;
                // 找到左子树的最右节点
                TreeNode preNode = left;
                while (preNode.right != null) {
                    preNode = preNode.right;
                }
                preNode.right = cur.right;
                cur.left = null;
                cur.right = left;
            }
            // 存在左孩子, 左孩子变为右孩子
            cur = cur.right;
        }
    }
}
